from odoo import _, api, fields, models
from odoo.exceptions import ValidationError


class RmaReWorkWizard(models.TransientModel):
    _name = "rma.rework.wizard"
    _description = "RMA Rework Wizard"

    product_id = fields.Many2one("product.product", string="Product")
    product_uom_qty = fields.Float(string="Quantity awaiting maintenance", digits="Product Unit of Measure")
    to_done_qty = fields.Float(string="Pending Quantity", digits="Product Unit of Measure")
    product_uom = fields.Many2one(comodel_name="uom.uom", string="Unit of measure")
    rma_id = fields.Many2one('rma')
    rework_bom_id = fields.Many2one('s.rework.bom', string='Rework Bom')

    @api.model
    def default_get(self, fields_list):
        res = super().default_get(fields_list)
        rma_ids = self.env.context.get("active_ids")
        rma = self.env["rma"].browse(rma_ids)
        if len(rma) > 1:
            raise ValidationError(_('Merge maintenance is not allowed!'))

        to_done_qty = 0
        product_uom_qty = rma.remaining_qty
        res.update(
            rma_id=rma.id,
            product_id=rma.product_id.id,
            product_uom_qty=product_uom_qty,
            to_done_qty=product_uom_qty,
        )
        return res

    def action_done(self):
        self.ensure_one()

        self.rma_id.create_rework(self.to_done_qty, self.rework_bom_id)

